/*
 * Copyright (c) 2002 David Corbin and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v0.5
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 * 	  David Corbin - initial implementation
 */
package net.sourceforge.p4eclipse.core.util;

import java.io.BufferedReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

/**  
 * Parsing engine for Perforce forms.  
 * 
 * This will parse any form, returning all field value as Strings.  For other
 * more complex fields, derived classes can register something to parse the field
 * contents more throughly.  See ClientForm for an example.
 * 
 * @version 	1.0
 * @author     <a href="mailto:dcorbin@users.sourceforge.net">David Corbin</a>
 */
public class Form
{
	int fieldCount()
	{
		return valueMap.size();
	}
	public  interface FieldParser
	{
		public void addLine(String line);
		public Object parse();
	}
	protected void registerFieldParser(String fieldName,FieldParser fieldParser)
	{
		parserMap.put(fieldName,fieldParser);
	}
	protected void setField(String fieldName, String value)
	{
		valueMap.put(fieldName,value);
	}
	protected Object getField(String fieldName)
	{
		return valueMap.get(fieldName);
	}
	protected void putField(String fieldName, Object value)
	{
		valueMap.put(fieldName,value);
	}
	private Map valueMap = new HashMap();
	private Map parserMap = new HashMap();
	public  static class BasicFieldParser implements FieldParser
	{
		protected StringBuffer buffer = new StringBuffer();
		public void addLine(String line)
		{
			buffer.append(line);
			buffer.append('\n');
		}
		public Object parse()
		{
			return buffer.toString().trim();
		}
	}
	private FieldParser subParser(String fieldName)
	{
		FieldParser subParser = (FieldParser)parserMap.get(fieldName);		
		if (subParser == null)
			subParser = new BasicFieldParser();
		return subParser;
	}

	public void parse(String inputText)
		throws java.io.IOException
	{
		parse(new StringReader(inputText));
	}
	public void parse(Reader inputReader)
		throws java.io.IOException
	{
		BufferedReader reader = new BufferedReader(inputReader);
		Form.FieldParser subParser = null;
		String line;
		while ((line = reader.readLine()) != null)
		{
			if (line.length() > 0 && line.charAt(0) == '#')
				continue;
			int colonPosition = line.indexOf(':');
			if (colonPosition > 0)
			{

				String fieldName = line.substring(0,colonPosition);
				subParser = subParser(fieldName);
				
				line = line.substring(colonPosition+1).trim();
				do
				{
					subParser.addLine(line);
				}
				while ((line = reader.readLine()) != null
						&& line.length() > 0);
				putField(fieldName,subParser.parse());
				subParser = null;
			}
		}
	}
}
